<template>
  <div>
    <div id="search">
      <el-form :inline="true" :model="roleSearch" class="demo-form-inline">
        <el-form-item label="角色名">
          <el-input v-model="roleSearch.roleCh" placeholder="请输入角色名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onSearchSubmit">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div id="header-bth">
      <el-button type="primary" size="small" icon=el-icon-circle-plus-outline @click="showAddScore">添加</el-button>
    </div>
    <div id="role-table">
      <el-table
          :data="tableData"
          stripe
          style="width: 100%">
        <el-table-column label="角色名">
          <template slot-scope="scope">
            <span style="margin-left: 20px">{{ scope.row.roleCh }}</span>
          </template>
        </el-table-column>
        <el-table-column label="权限字符">
          <template slot-scope="scope">
            <span>{{ scope.row.roleEn }}</span>
          </template>
        </el-table-column>
        <el-table-column label="描述">
          <template slot-scope="scope">
            <span>{{ scope.row.comments }}</span>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" width="150px">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280px">
          <template slot-scope="scope">
            <el-button
                icon="el-icon-edit"
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">
            </el-button>
            <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="handleDelete(scope.row.roleId)">
            </el-button>
            <el-button
                size="mini"
                type="success"
                @click="handleAuth(scope.$index, scope.row)">分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div id="nav-page">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="pageSizes"
          :current-page="roleSearch.page"
          :page-size="roleSearch.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <!--添加 编辑角色信息弹窗-->
    <el-dialog :title="dialogTitle" :visible.sync="addRoleFormVisible" width="50%" @close="clearInfo">
      <el-form :model="roleForm" ref="roleInfo" :rules="roleRules" label-width="90px" size="medium">
        <el-input v-model="roleForm.roleId" autocomplete="off" v-show="false"></el-input>
        <el-form-item label="角色名" prop="roleCh">
          <el-input v-model="roleForm.roleCh" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="权限字符" prop="roleEn">
          <el-input v-model="roleForm.roleEn" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="comments">
          <el-input v-model="roleForm.comments" show-word-limit maxlength="100" type="textarea"
                    :autosize="{ minRows: 5, maxRows: 10 }" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
    <!--分配权限-->
    <el-dialog title="分配权限" :visible.sync="authTreeVisible" width="30%" @close="clearNode">
      <el-tree
          ref="tree"
          :data="treeData"
          show-checkbox
          node-key="id"
          :default-checked-keys="defaultCheckedKeys"
          :default-expand-all="true"
          :props="defaultProps">
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addRolePermissions">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {addOrUpdateRoleApi, addPermisson, deleteUser, roleList, updateUser} from "@/request/api";
import {listToTree} from "@/util/treeUtil";
import instance from "@/request/request";

export default {
  name: "RoleView",
  data() {
    return {
      tableData: [],
      pageSizes: [3, 5, 10, 15],
      total: 0,
      addRoleFormVisible: false,
      authTreeVisible: false,
      authTreeCheckedKeys: [],
      dialogTitle: '',
      roleForm: {},
      roleSearch: {  // 搜索数据
        page: 1,
        limit: 5
      },
      roleRules: {
        roleCh: [{required: true, message: '请输入角色名', trigger: 'blur'}],
        roleEn: [{required: true, message: '请输入角色标识', trigger: 'blur'}]
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      /*权限树形结构数据*/
      treeData: [],
      roleId:'',
      defaultCheckedKeys:[],
    }
  },
  created() {
    this.getroleList()
  },
  methods: {
    //获取角色信息
    getroleList() {
      roleList(this.roleSearch).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.role
          this.total = res.data.total
          return
        }
        this.$message.error(res.msg)
      }).catch(erro => {
        this.$message.error("请求失败")
      })
    },
    // 编辑角色
    handleEdit(index, row) {
      this.dialogTitle = "编辑角色"
      this.addRoleFormVisible = true
      let form = Object.assign({}, row)
      this.roleForm = form
    },
    //更新和添加用户信息
    submit() {
      this.$refs.roleInfo.validate(valid => {
        if (!valid) {
          this.$message.warning("请输入必要数据")
          return
        }
        //  发送异步请求   实现角色的添加或修改    roleId
        addOrUpdateRoleApi(this.roleForm).then(response => {
          if (response.code == 200) {
            this.$message.success(response.msg)
            this.addRoleFormVisible = false
            this.roleForm = {}
            this.getroleList()
            return
          }
          this.$message.warning(response.msg)
        }).catch(error => {
          this.$message.error("请求失败")
        })
      })

    },
    // 删除角色
    handleDelete(id) {
     this.$confirm('确认要删除？', '系统提示', {
       confirmButtonText: '确定',
       cancelButtonText: '取消',
       type: 'warning'
     }).then(async () => {
       try {
         const res=await instance.delete("/role/delete/"+id)
         if(res.code==200){
           this.$message.success(res.msg)
           this.getroleList()
           return
         }
         this.$message.warning(res.msg)
       }catch (e) {
         this.$message.error("请求失败")
       }
     }).catch(() => {
       this.$message({
         type: 'info',
         message: '已取消！'
       })
     })

    },
    /*分配权限*/
    async handleAuth(index, row) {
      this.roleId=row.roleId
      let {data} = await instance.get("/permission/list")
      //遍历返回的权限列表 将数据处理成树形结构需要的样式
      let permissions = data.map(p => {
        return {
          label: p.title,
          id: p.id,
          pid: p.pid
        }
      })
      // 通过工具类将数据挂载成树形结构
      this.treeData = listToTree(permissions)
      let {data:btnPermission} =  await instance.get("/role/showper",{params:{
        roleId:row.roleId
        }})
      console.log("===="+btnPermission)
      this.defaultCheckedKeys = btnPermission
      this.authTreeVisible = true
    },
    addRolePermissions() {
      this.authTreeCheckedKeys = [...this.$refs.tree.getHalfCheckedKeys(), ...this.$refs.tree.getCheckedKeys()]
       const roleId=this.roleId
       const perId=this.authTreeCheckedKeys
       addPermisson({roleId,perId}).then(res=>{
         if(res.code==200){
           this.$message.success(res.msg)
           this.authTreeVisible=false
         }
       }).catch(erro=>{
         this.$message.error("请求失败")
       })
    },
    // 搜索角色
    onSearchSubmit() {
      this.roleSearch.page = 1
      this.roleSearch.limit = 5
      this.getroleList()
    },
    // 改变每页显示的条数触发
    handleSizeChange(val) {
      this.roleSearch.limit = val;
      this.getroleList()
    },
    // 改变页码触发
    handleCurrentChange(val) {
      this.roleSearch.page = val;
      this.getroleList()
    },
    // 显示弹出等
    showAddScore() {
      this.dialogTitle = "添加角色"
      this.addRoleFormVisible = true
      this.roleForm = {}
    },
    //清空校验规则
    clearInfo() {
      this.$refs.roleInfo.clearValidate()
    },
    clearNode(){
      this.defaultCheckedKeys=[]
    }
  },
}
</script>

<style scoped>
#search {
  width: 100%;
  height: 50px;
  border-bottom: 1px solid #eee;
}

#search, #header-bth, #nav-page {
  margin: 15px;
}

#role-table {
  width: 100%;
}
</style>
